package com.zzzy.framework.validator;

import com.zzzy.framework.common.annotation.RangeValuesCheck;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Description: 参数值范围 校验
 *
 * @author fc
 * @date 2024/4/11
 */
public class RangeValuesCheckValidator implements ConstraintValidator<RangeValuesCheck, Object> {

    private String[] strValues;
    private int[] intValues;
    private Class<?> clazz;
    private boolean allowBlank;
    private boolean allowNull;

    @Override
    public void initialize(RangeValuesCheck constraintAnnotation) {
        strValues = constraintAnnotation.stringValueRange();
        intValues = constraintAnnotation.intValueRange();
        clazz = constraintAnnotation.enumValueRange();
        allowBlank = constraintAnnotation.allowBlank();
        allowNull = constraintAnnotation.allowNull();
    }

    @SneakyThrows
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (allowBlank && StringUtils.isBlank((CharSequence) value)){
            return Boolean.TRUE;
        }
        if (allowNull && Objects.isNull(value)){
            return Boolean.TRUE;
        }
        if (clazz.isEnum()) {
            Object[] objects = clazz.getEnumConstants();
            //此处方法 getValue 需要根据自己项目枚举的命名而变化
            Method method = clazz.getDeclaredMethod("getValue");
            for (Object obj : objects) {
                String expectValue = String.valueOf(method.invoke(obj));
                if (expectValue.equals(String.valueOf(value))) {
                    return true;
                }
            }
        } else {
            if (value instanceof String) {
                for (String intValue : strValues) {
                    if (intValue.equals(value)) {
                        return true;
                    }
                }
            } else if (value instanceof Integer) {
                for (Integer intValue : intValues) {
                    if (intValue.equals(value)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
